<?php
namespace Poi\EttsBundle\Model;

/**
 * @author Ricardo J. Vazquez
 * 
 * Collection of Driver models
 */
class Drivers extends Collection
{
	public function init(){
	}
	
	/**
	* Loads the collection with Driver models
	*
	* @param $col 
	*/
	protected function loadDrivers(Collection $col){
		$sql = "SELECT 
					D1.LicenseNumber AS 'LicenseNumber', 
					D1.Name, 
					D1.Direction, 
					D1.Height, 
					UNIX_TIMESTAMP(D1.Expiration) AS 'Expiration',
					E1.EyeColor, 
					S1.Sex,
					DT.Type
				FROM Driver D1
					Inner join Eyes E1 on D1.Ojos=E1.idEyes
					Inner join Sex S1 on D1.sexo=S1.idSex
					Inner join DriverType DT on D1.TipoConductor=DT.idDriverType ";

		$loadStmt = $this->conn->prepare($sql);
		
		$loadStmt->execute();
		
		$drivers = $loadStmt->getWrappedStatement()->fetchAll(
			\PDO::FETCH_CLASS, 
			"Poi\\EttsBundle\\Model\\Driver", 
			array($this->conn)
		);
		
		$count = 0;
		foreach($drivers as $driver){
			$driver->setLoaded(true);
			$this->addItem($driver, $count++);
		}
	}
	
	public function toXML(\SimpleXMLElement &$xml=null){
		$return = false;
		if(is_null($xml)){
			$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?><xmlresponse></xmlresponse>');
			$return = true;
		}
		
		$length = $this->length();
		
		$driversXML = $xml->addChild('drivers');
		
		for($i = 0; $i < $length; $i++)
		{
			$this->getItem($i)->toXML($driversXML);
		}
				
		if($return){		
			return $xml->asXML();
		}
	}
}